package yxy.game.pm2.module.shop;

import com.alibaba.fastjson.JSONObject;
import org.joda.time.DateTime;
import org.joda.time.Seconds;
import yxy.apple.util.RandomUtility;
import yxy.apple.util.RandomUtility.Weight;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.breakshop;
import yxy.cherry.data.bean.config;
import yxy.cherry.data.bean.secretshop;
import yxy.cherry.data.bean.shop;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class MerchantModule extends ShopModule {

    // bean===========================================================================
    private int freeTimes; // 免费刷新次数
    private DateTime freeRefreshTime; // 弃用
    private int resetTimes;// 付费刷新次数次数
    private DateTime refreshTime; //  刷新时间（隔天刷新次数）


    public int getFreeTimes() {
        return freeTimes;
    }

    public void setFreeTimes(int freeTimes) {
        this.freeTimes = freeTimes;
    }

    public DateTime getFreeRefreshTime() {
        return freeRefreshTime;
    }

    public void setFreeRefreshTime(DateTime freeRefreshTime) {
        this.freeRefreshTime = freeRefreshTime;
    }

    public int getResetTimes() {
        return resetTimes;
    }

    public void setResetTimes(int resetTimes) {
        this.resetTimes = resetTimes;
    }

    public DateTime getRefreshTime() {
        return refreshTime;
    }

    public void setRefreshTime(DateTime refreshTime) {
        this.refreshTime = refreshTime;
    }

    // func===========================================================================

    //商店刷新消费
    public Currency MerchantRefreshCost() {
        if (getFreeTimes() > 0) {
            return null;
        }

        Currency cost = ShopRefreshCost();

        //已付费刷新次数
        int hasRefreshTimes = RefreshUpper() - getResetTimes();

        //元宝增加次数
        int times = hasRefreshTimes / 2;

        config data = DataCenter.getData(3, config.class);
        JSONObject jsonObject = JSONObject.parseObject(data.getValue());
        Integer increase = jsonObject.getInteger("increase");
        cost.setNumber(cost.getNumber() + times * increase);

        return cost;
    }

    /**
     * 是否可以刷新
     */
    public boolean canRefresh() {
        // 免费剩余次数>0 或 付费次数<上限
        return getFreeTimes() > 0 || getResetTimes() > 0;
    }

    /**
     * 刷新商品
     */
    public void _refresh() {
        shuffleGoods();
        set();
    }

    // static===========================================================================

    static private shop data = data(9999);

    /**
     * 商店上限
     */
    public static int ShopUpper() {
        return data.getShopmax();
    }

    /**
     * 商店刷新消费
     */
    public static Currency ShopRefreshCost() {
        return Currency.create(data.getRecosttype(), data.getRecostid(), data.getRecostnum());
    }

    /**
     * 付费刷新次数上限
     */
    public static int RefreshUpper() {
        return data.getRenum();
    }

    /**
     * 免费刷新次数上限
     */
    public static int RefreshFreeUpper() {
        return data.getRefreenum();
    }

    /**
     * 商店免费刷新增长时间(秒)
     */
    public static Seconds RefreshFreeTime() {
        return Seconds.seconds(data.getRefreetime());
    }

    public static String key(String playerCode) {
        return String.format(key(), playerCode, "MERC");
    }

    public static MerchantModule get(String playerCode) {
        try {
            MerchantModule module = getv(key(playerCode));
            if (module == null) {
                module = MySQLCacheDAO.getV(key(playerCode), MerchantModule.class);
                if (module != null) {
                    module.set();
                }//把数据同步到redis
            }

            String md5 = DataCenter.getMD5(breakshop.class);
            if (module == null) {
                module = create(playerCode, md5);
            } else {
                module.checkMD5(md5);
            }
            return module;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static MerchantModule create(String playerCode, String md5) {
        MerchantModule module = new MerchantModule();
        module.setPlayerCode(playerCode);
        module.setDataMD5(md5);
        DateTime now = DateTime.now();
        module.setFreeRefreshTime(now);
        module.setRefreshTime(now);
        module.setFreeTimes(RefreshFreeUpper());
        module.setResetTimes(RefreshUpper());
        module.shuffleGoods();
        module.set();
        return module;
    }

    // extends===========================================================================

    //刷新的商品信息封装到缓存
    @Override
    protected void shuffleGoods() {
        Collection<breakshop> datas = shuffleDatas();
        DateTime now = DateTime.now();
        ArrayList<Goods> goodslist = new ArrayList<>();
        for (breakshop data : datas) {
            Goods goods = new Goods();
            goods.setId(data.getId());
            goods.setDataId(data.getId());
            goods.setSell(0);
            goods.setUpdateTime(now);
            goodslist.add(goods);
            if (goodslist.size() >= ShopUpper()) {
                break;
            }
        }
        setGoods(goodslist);
    }

    //刷新的商品信息
    private Collection<breakshop> shuffleDatas() {
        PlayerBean playerBean = PlayerBean.get(getPlayerCode());
        int level = playerBean.getLevel();
        Map<String, breakshop> datas = DataCenter.getAllData(breakshop.class);
        Map<String, secretshop> secretdatas = DataCenter.getAllData(secretshop.class);
        secretshop secret = null;
        for (secretshop data : secretdatas.values()) {
            if (secret == null) {
                secret = data;
            }
            if (level >= data.getPlayerlv() && data.getPlayerlv() < secret.getPlayerlv()) {
                secret = data;
            }
        }

        ArrayList<Secret> secrets = new ArrayList<>();
        for (int i = 0; i < secret.getCommodityid().length; i++) {
            int id = secret.getCommodityid()[i];
            int weight = secret.getPercent()[i];
            if (id > 0 && weight > 0) {
                secrets.add(new Secret(id, weight));
            }
        }
        ArrayList<breakshop> result = new ArrayList<>();

        List<Secret> list = RandomUtility.randomWeight(secrets, null, ShopUpper());
        for (Secret s : list) {
            breakshop data = datas.get(String.valueOf(s.id));
            if (data != null) {
                result.add(data);
            }
        }
        return result;
    }

    //存储到数据库的方法
    public static void saveToDB(String playerCode) {
        try {
            String key = key(playerCode);
            if (touch(key).isExists()) {
                MerchantModule merchantModule = getv(key(playerCode));
                if (merchantModule != null) MySQLCacheDAO.setV(key, merchantModule);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //从redis移走数据的操作
    public static void removeAllFromRedis(String playerCode) {
        try {
            touch(key(playerCode)).delete();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void set() {
        try {
            setv(key(getPlayerCode()), this);
        } catch (RedisException e) {
        }
    }

    private class Secret implements Weight {
        int id;
        int weight;

        public Secret(int id, int weight) {
            this.id = id;
            this.weight = weight;
        }

        @Override
        public int getWeight() {
            return weight;
        }
    }
}
